package org.recursed.simpleweather;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import org.recursed.simpleweather.forecast.FetchForecast;
import org.recursed.simpleweather.forecast.NWSWeatherObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

public class WeatherGallery {

	private SimpleWeather owner;
	private LocationManager locationManager;
	private Spinner locationChooser;
	
	private Handler handler;
	
	public WeatherGallery(SimpleWeather owner) {
		this.owner = owner;
		this.locationManager = owner.getLocationManager();
		this.locationChooser = (Spinner) owner.findViewById(R.id.locationChooser);
		int count = locationManager.getLocationCount();
		handler = new Handler();
		ArrayAdapter<String> locationAdapter = new ArrayAdapter<String>(owner.getApplicationContext()
				,android.R.layout.simple_spinner_item);
		for (int x=0; x<1; x++) {
			String[] location = locationManager.getLocation(x);
			locationAdapter.add(location[0]);
			FetchForecast ff = new FetchForecast(location[1], location[2], this);
			(new Thread(ff)).start();
		}
		locationChooser.setAdapter(locationAdapter);
	}
	
	public void gotWeather(final NWSWeatherObject nwo) {
		Thread X =  new Thread() {
			public void run() {
				updateWeather(nwo);
			}
		};
		handler.post(X);
	}
	
	public void updateWeather(NWSWeatherObject nwo) {
		ImageView i = (ImageView) owner.findViewById(R.id.image1);
		if ( i == null) {
			// view has bailed on us- just fail fast
			return;
		}
		try {
			List<String> conditions = nwo.getConditionIconLinks();
			String first = conditions.get(0);
			Bitmap bm = getImage(first);
			i.setImageBitmap(bm);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		TextView t = (TextView) owner.findViewById(R.id.day);
		t.setText("Tomorrow");
	}

    private Bitmap getImage(String httpLocation) throws IOException {
    	Bitmap result = null;
    	URL url = new URL(httpLocation);
    	URLConnection con = url.openConnection();
    	BufferedInputStream in = new BufferedInputStream(con.getInputStream());
    	result = BitmapFactory.decodeStream(in);
    	in.close();
    	return result;
    }
 
	
}
